
import { login, logout, getInfo } from "@/api/user";
// import { login, getInfo} from '@/api/user'
import { getToken, setToken, removeToken } from "@/utils/auth";
// import { resetRouter } from "@/router";

// const getDefaultState = () => {
//   return {
//     token: getToken(),
//     name: "",
//     avatar: ""
//   };
// };

const state = {
  // 设置token为共享状态 初始化vuex的时候 就先从缓存中读取
  token: getToken(),
  // 定义一个空的对象 不是null 因为后边我要开发userInfo的属性给别人用  userInfo.name
  userInfo: {}
};

const mutations = {
  setToken(state, token) {
    state.token = token;
    setToken(state.token);
    console.log(token);
  },
  removeToken(state) {
    state.token = null;
    removeToken();
  },
  // 获取用户信息
  setUserInfo(state, userInfo) {
    // console.log(userInfo);
    state.userInfo = { ...userInfo };
  },
  // 删除用户信息
  reomveUserInfo(state) {
    state.userInfo = {};
  }
};

const actions = {
  async login(context, data) {
    console.log(data);
    const result = await login(data);
    console.log(result);
    const tk = result.data.token;
    console.log(tk);
    context.commit("setToken", tk);
  },
  async getInfo(context) {
    const user = await getInfo();
    context.commit("setUserInfo", user.data);
  },
  async logout(context) {
    context.commit("removeToken");
    context.commit("reomveUserInfo");
    // resetRouter();
    // context.commit("permission/setRoutes", [], { root: true });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};